package com.hafu.service;

import com.hafu.dao.RuKuDetailDao;
import com.hafu.dao.RuKuMainDao;
import com.hafu.model.KuCun;
import com.hafu.model.RuKuDetail;
import com.hafu.model.RuKuMain;
import com.hafu.util.DbUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

public class RuKuService {
    private RuKuMainDao ruKuMainDao = new RuKuMainDao();
    private RuKuDetailDao ruKuDetailDao = new RuKuDetailDao();
    private KuCunService kuCunService = new KuCunService();
    public boolean addRuKu(RuKuMain ruku){
        Connection conn = DbUtil.getConn();
        try {
            conn.setAutoCommit(false);
            int i = ruKuMainDao.addRuKuMain(ruku, conn);
            if (i>0){
                ArrayList<RuKuDetail> rukudetailList = ruku.getRukuDetailList();
                for (RuKuDetail rukuDetail:rukudetailList){
                    rukuDetail.setRukuId(i);
                    boolean b = ruKuDetailDao.addRuKuDetail(rukuDetail, conn);
                    if (!b){
                        conn.rollback();
                        return false;
                    }
                    //商品添加到库存
                    KuCun kuCunBySpName = kuCunService.getKuCunBySpName(rukuDetail.getSpName(), conn);
                    if (kuCunBySpName==null){
                        //仓库没有
                        KuCun kuCun = new KuCun();
                        kuCun.setSpname(rukuDetail.getSpName());
                        kuCun.setNum(rukuDetail.getNum());
                        boolean b1=kuCunService.addRuKu(kuCun, conn);
                        if (!b1){
                            conn.rollback();
                            return false;
                        }
                    }else {
                        int num =kuCunBySpName.getNum()+rukuDetail.getNum();
                        kuCunBySpName.setNum(num);
                        boolean b1 = kuCunService.updateKuCun(kuCunBySpName, conn);
                        if (!b1){
                            conn.rollback();
                            return false;
                        }
                    }
                }
                conn.commit();
                conn.setAutoCommit(true);
                return true;
            }else {
                conn.rollback();
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
    public ArrayList<RuKuMain> geRuKuList(RuKuMain ruku){
        return ruKuMainDao.geRuKuMainByName(ruku);
    }public boolean updateRuKu(RuKuMain rukuMain){
        return ruKuMainDao.updateRuKu(rukuMain);
    }
}
